using Castle.MonoRail.Framework;
using System.Web.Security;
using System.Security.Principal;

namespace WineCellar.Web
{
    public static class SecurityHelper
    {
        private const string CurrentUser="CurrentUser";
        public static RolePrincipal GetCurrentUser(IEngineContext context)
        {
            return (RolePrincipal)context.Session[CurrentUser];
        }
        
        public static bool Authenticate(Controller controller, string userName, string password, bool rememberCredentials,
            string returnUrl)
        {
            //TODO: Implement rememberCredentials using Cookie
            bool isAuthenticated = Membership.ValidateUser(userName, password);
            if (isAuthenticated)
            {
                GenericIdentity identity = new GenericIdentity(userName, Membership.Provider.GetType().FullName);
                controller.Context.Session[CurrentUser] = new RolePrincipal(identity);                
            }

            return isAuthenticated;
        }
		public static bool Logout(IEngineContext context)
        {
            RolePrincipal principal = GetCurrentUser(context);
            if (principal != null)
            {
                context.Session.Remove(CurrentUser);
                context.Session.Remove("memberShipUser");
                return true;
            }
            else
                return false;
            
        }
    }
}
